package com.example.gateway.interceptor;

import com.example.gateway.exception.AuthException;
import com.example.gateway.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token == null ) {
            throw new AuthException(400,"缺少token");
        }
        if(!token.startsWith("Bearer")){
            throw new AuthException(400,"token缺少前缀Bearer");
        }
        if (token.length() < 8) {
            throw new AuthException(400, "缺少token");
        }
        token = token.substring(7);
        Claims claims = null;
        try {
            claims = JwtUtil.parseToken(token);
        }catch (Exception e){
            throw new AuthException(400, "token无效");
        }
        Long userId = claims.get("userId", Long.class);
        String phone = claims.get("phone", String.class);
        Object redisValue = redisTemplate.opsForValue().get("USERID:" + userId);
        if (redisValue == null) {
            throw new AuthException(400, "token无效或者已过期");
        }

        request.setAttribute("Authorization-UserId", String.valueOf(userId));
        request.setAttribute("Authorization-Phone", phone);

        return true;
    }
}